package com.example.controller;

import com.example.common.Result;
import com.example.entity.Grade;
import com.example.service.GradeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/grade")
public class GradeController {

    @Autowired
    private GradeService gradeService;

    @PostMapping("/add")
    public Result<Boolean> addGrade(@RequestBody Grade grade) {
        boolean result = gradeService.addGrade(grade);
        return Result.success(result);
    }

    @PutMapping("/update")
    public Result<Boolean> updateGrade(@RequestBody Grade grade) {
        // 校验ID是否存在
        if (grade.getId() == null) {
            return Result.error("ID不能为空");
        }
        boolean result = gradeService.updateGrade(grade);
        return result ? Result.success(true) : Result.error("更新失败");
    }

    @DeleteMapping("/delete/{id}")
    public Result<Boolean> deleteGrade(@PathVariable Long id) {
        // 校验ID是否存在
        if (id == null) {
            return Result.error("ID不能为空");
        }
        boolean result = gradeService.deleteGrade(id);
        return result ? Result.success(true) : Result.error("删除失败");
    }

    @GetMapping("/get/{id}")
    public Result<Grade> getGradeById(@PathVariable Long id) {
        // 校验ID是否存在
        if (id == null) {
            return Result.error("ID不能为空");
        }
        Grade grade = gradeService.getGradeById(id);
        return grade != null ? Result.success(grade) : Result.error("未找到该成绩");
    }

    @GetMapping("/list")
    public Result<List<Grade>> getGradeList(Grade grade) {
        List<Grade> gradeList = gradeService.getGradeList(grade);
        return Result.success(gradeList);
    }

    @GetMapping("/student/{studentId}")
    public Result<List<Grade>> getGradesByStudentId(@PathVariable Long studentId) {
        // 校验学生ID是否存在
        if (studentId == null) {
            return Result.error("学生ID不能为空");
        }
        List<Grade> gradeList = gradeService.getGradesByStudentId(studentId);
        return Result.success(gradeList);
    }

    @GetMapping("/course/{courseId}")
    public Result<List<Grade>> getGradesByCourseId(@PathVariable Long courseId) {
        // 校验课程ID是否存在
        if (courseId == null) {
            return Result.error("课程ID不能为空");
        }
        List<Grade> gradeList = gradeService.getGradesByCourseId(courseId);
        return Result.success(gradeList);
    }

    @GetMapping("/statistics/{courseId}")
    public Result<Map<String, Object>> getCourseStatistics(@PathVariable Long courseId) {
        // 校验课程ID
        if (courseId == null) {
            return Result.error("课程ID不能为空");
        }

        // 获取该课程的所有成绩
        List<Grade> grades = gradeService.getGradesByCourseId(courseId);

        if (grades == null || grades.isEmpty()) {
            return Result.success(Collections.singletonMap("message", "暂无成绩数据"));
        }

        // 计算平均分、最高分、最低分
        double averageScore = grades.stream()
                .mapToDouble(Grade::getScore)
                .average()
                .orElse(0.0);

        double maxScore = grades.stream()
                .mapToDouble(Grade::getScore)
                .max()
                .orElse(0.0);

        double minScore = grades.stream()
                .mapToDouble(Grade::getScore)
                .min()
                .orElse(0.0);

        // 统计各分数段人数
        Map<String, Integer> scoreDistribution = new LinkedHashMap<>();
        scoreDistribution.put("0-59", 0);
        scoreDistribution.put("60-69", 0);
        scoreDistribution.put("70-79", 0);
        scoreDistribution.put("80-89", 0);
        scoreDistribution.put("90-100", 0);

        grades.forEach(grade -> {
            double score = grade.getScore();
            if (score < 60) {
                scoreDistribution.put("0-59", scoreDistribution.get("0-59") + 1);
            } else if (score < 70) {
                scoreDistribution.put("60-69", scoreDistribution.get("60-69") + 1);
            } else if (score < 80) {
                scoreDistribution.put("70-79", scoreDistribution.get("70-79") + 1);
            } else if (score < 90) {
                scoreDistribution.put("80-89", scoreDistribution.get("80-89") + 1);
            } else {
                scoreDistribution.put("90-100", scoreDistribution.get("90-100") + 1);
            }
        });

        Map<String, Object> result = new HashMap<>();
        result.put("averageScore", averageScore);
        result.put("maxScore", maxScore);
        result.put("minScore", minScore);
        result.put("distribution", scoreDistribution);

        return Result.success(result);
    }
}